#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>

void ChildWrite(int fd)
{
    char buffer[1024];
    int cnt=0;
    
    while(1)
    {
        //写入文件时，不需要写入'\0'
        snprintf(buffer,sizeof(buffer),"I am child,pid:%d,cnt:%d\n",getpid(),cnt++);
        write(fd,buffer,strlen(buffer));
        sleep(1);
    }

}

void FatherRead(int fd)
{
    char buffer[1024];

    while(1)
    {
        buffer[0]=0;
        //但读入时，需要预留'\0'空间，手动添加
        ssize_t n=read(fd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"child say:"<<buffer<<std::endl;
        }
    }
   
}

int main()
{
    //创建管道
    int fds[2]={0};
    int n =pipe(fds);

    if(n<0)
    {
        std::cout<<"pipe error"<<std::endl;
        return 1;
    }

    std::cout<<"fds[0]："<<fds[0]<<std::endl;
    std::cout<<"fds[1]："<<fds[1]<<std::endl;

    //创建子进程
    pid_t id=fork();
    if(id==0)
    {
        //子进程关闭读
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);

        exit(1);
    }

    //父进程关闭写
    close(fds[1]);
    FatherRead(fds[0]);
    waitpid(id,nullptr,0);
    close(fds[0]);


    return 0;
}